const fs = require('fs');
const path = require('path');
const exec = require('child_process').execSync;
const yaml = require('js-yaml');
const inquirer = require('inquirer');

const ymlStats = fs.statSync('electron-builder.yml', { throwIfNoEntry: false });
const outDir = fs.statSync('./out', { throwIfNoEntry: false })
if (ymlStats && ymlStats.isFile()) {
  exec('rm electron-builder.yml', { stdio: 'inherit' });
}
if (outDir && outDir.isDirectory()) {
  exec(`rm -rf out`, { stdio: 'inherit' });
}



const exeConf = {
	appId: "com.innodev.app",
	copyright: "Copyright © wuqiong",
  compression: "store",
	asar: false,
	directories: {
		output: "./out"
	},
	electronDownload: {
		mirror: "https://npm.taobao.org/mirrors/electron/"
	},
	win: {
		icon: "app.ico",
		target: ["nsis"]
	},
  files: [
    "./dist",
    "main.js",
    "package.json"
  ],
	nsis: {
		oneClick: false,
		perMachine: true,
		allowToChangeInstallationDirectory: true,
    installerIcon: "app.ico",
    uninstallerIcon: "app.ico",
    installerHeaderIcon: "app.ico"
	}
}

const getDate = () => {
  const date = new Date()
  const year = date.getFullYear()
  const month = (date.getMonth() + 1) >= 10 ? date.getMonth() + 1 : `0${date.getMonth() + 1}`
  const day = date.getDate()
  return `${year}-${month}-${day}`
}

// 命令行方式确定程序包配置
const genConf = async () => {
  const { productName, versionNum, moreScreen, bit } = await inquirer.prompt([
    {
      type: 'input',
      name: 'productName',
      message: '请输入包名: ',
      filter: function (val) {
        if (!val.replace('请输入包名: ', '').length) {
          return `未命名-${getDate()}`
        }
        return `${val}-${getDate()}`
      }
    },
    {
      type: 'input',
      name: 'versionNum',
      message: '请输入版本号: ',
      default: '1.0.0'
    },
    {
      type: 'confirm',
      message: '请确认是否显示在副屏, 默认 (No):',
      name: 'moreScreen',
      default: false
    },
    {
      type: 'confirm',
      name: 'bit',
      message: '请确认是否打包为32位程序, 默认 (No):',
      default: false
    }
  ])

  let pkg = fs.readFileSync('./package.json', 'utf8')
  pkg = JSON.parse(pkg)
  pkg.version = versionNum
  pkg.moreScreen = moreScreen

  fs.writeFileSync('./package.json', JSON.stringify(pkg), 'utf8')

  const ymlFile = yaml.dump({
    productName: productName,
    ...exeConf
  });
  fs.writeFileSync('electron-builder.yml', ymlFile, 'utf-8');

  if (bit) {
    exec('electron-builder --win --ia32', { stdio: 'inherit' });
  } else {
    exec('electron-builder', { stdio: 'inherit' });
  }

  if (ymlStats && ymlStats.isFile()) {
    exec('rm electron-builder.yml', { stdio: 'inherit' });
  }
}

genConf();